package com.timedomain.him.remake.ui;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.timedomain.him.remake.Program;
import com.timedomain.him.remake.R;
import com.timedomain.him.remake.core.BassUtils;
import com.timedomain.him.remake.core.ChannelCreator;
import com.timedomain.him.remake.core.OneshotPlayer;
import com.timedomain.him.remake.ui.common.CallingActivity;
import com.timedomain.him.remake.utils.BaseActivity;
import com.timedomain.him.remake.utils.FileUtils;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class EmergencyVoiceActivity extends BaseActivity {

    ListView listMain = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_emergency);
        listMain = findViewById(R.id.listEmergencyMain);
        new Thread(this::LoadList).start();
    }

    private void LoadList(){
        ArrayList<EmergencyVoiceEntry> list = new ArrayList<>();


        String voicePath = "emergency";
        String phonePath = FileUtils.pathCombine(voicePath,"call");

        // 载入电话列表
        List<String> files = FileUtils.listFiles(phonePath,(dir, name) -> name.toLowerCase().endsWith(".ogg"));

        Collections.sort(files, (o1, o2) -> o1.compareTo(o2));
        for (String f :files) {
            EmergencyVoiceEntry entry = ReadOne(f,this);
            entry.isTelephone = true;
            list.add(entry);
        }
        // 载入安全语音列表
        files = FileUtils.listFiles(voicePath,(dir, name) -> name.toLowerCase().endsWith(".ogg"));
        Collections.sort(files, (o1, o2) -> o1.compareTo(o2));
        for (String f :files) {
            EmergencyVoiceEntry entry = ReadOne(f,this);
            entry.isTelephone = false;
            if(!entry.path.startsWith(phonePath)){

                list.add(entry);
            }
        }

        runOnUiThread(() -> {
            EmergencyVoiceListAdapter adapter = new EmergencyVoiceListAdapter(EmergencyVoiceActivity.this,list);
            listMain.setAdapter(adapter);
            findViewById(R.id.listEmergencyLoading).setVisibility(View.GONE);
            listMain.setVisibility(View.VISIBLE);
            listMain.startAnimation(AnimationUtils.loadAnimation(EmergencyVoiceActivity.this,android.R.anim.fade_in));
        });

    }

    private EmergencyVoiceEntry ReadOne(String audiopath,Context ctx){
        EmergencyVoiceEntry entry = new EmergencyVoiceEntry();
        entry.path = audiopath;
        String fileName = entry.path = audiopath;
        String textName = FileUtils.pathCombine(FileUtils.getParentPath(fileName),FileUtils.getFileNameWithoutExtension(fileName)+".txt");
        try(BufferedReader br = new BufferedReader(new InputStreamReader(Program.openAsset(ctx,textName)))){
            entry.title = br.readLine();
            entry.desc = br.readLine();
        }catch (Exception ex){
            entry.desc = fileName;
            entry.title = fileName;
            ex.printStackTrace();
        }
        return entry;
    }


    public static class EmergencyVoiceEntry{
        public boolean isTelephone;
        public String title;
        public String desc;
        public String path;
    }

    private boolean disableButtonTempory = false;

    public class EmergencyVoiceListAdapter extends ArrayAdapter<EmergencyVoiceEntry> {

        public EmergencyVoiceListAdapter(@NotNull Context context, @NotNull List<EmergencyVoiceEntry> objects) {
            super(context, R.layout.list_emergency, objects);
        }

        @NotNull
        @Override
        public View getView(int position, @Nullable View convertView, @NotNull ViewGroup parent) {
            if(convertView == null){
                convertView = getLayoutInflater().inflate(R.layout.list_emergency,null,false);
            }
            TextView txtTitle = convertView.findViewById(R.id.listEmergencyItemTitle);
            TextView txtDesc = convertView.findViewById(R.id.listEmergencyItemDescription);
            ImageButton btnPlay = convertView.findViewById(R.id.listEmergencyItemPlayButton);
            EmergencyVoiceEntry entry = getItem(position);
            txtTitle.setText(entry.title);
            txtDesc.setText(entry.desc);
            btnPlay.setTag(entry);
            if(disableButtonTempory){
                btnPlay.setEnabled(false);
                btnPlay.setAlpha(0.5f);
            }
            else{
                btnPlay.setEnabled(true);
                btnPlay.setAlpha(1f);
            }
            btnPlay.setOnClickListener(EmergencyVoiceActivity.this::onPlayPressed);
            if(!entry.isTelephone){
                btnPlay.setImageResource(R.mipmap.player_notify_play);
            }
            else{
                btnPlay.setImageResource(R.drawable.call1_1);
            }
            return convertView;
        }


    }
    Handler hWnd = new Handler();
    protected void onPlayPressed(View v){
        disableButtonTempory = true;
        ((EmergencyVoiceListAdapter) listMain.getAdapter()).notifyDataSetChanged();
        hWnd.postDelayed(()->{
            disableButtonTempory=false;
            ((EmergencyVoiceListAdapter) listMain.getAdapter()).notifyDataSetChanged();
            },1000);

        EmergencyVoiceEntry entry = (EmergencyVoiceEntry) v.getTag();
        if(entry.isTelephone){
            CallingActivity.startNewCall(this,entry.path,false);
        }
        else{
            OneshotPlayer.StartSound(ChannelCreator.FromFile(this,entry.path));
        }
    }
}
